﻿using System;
using Ah.Testudin.Engine.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Ah.Testudin.Engine.UI.Elements.Debugging
{
    public class FpsScreenElement : ScreenElementBase
    {
        #region Private Member Variables

        private float _elapsedTime;

        private int _frameCount;

        private int _framesPerSecond;

        private readonly ITestudinRenderer _renderer;

        private readonly SpriteFont _spriteFont;

        #endregion

        #region Constructors

        public FpsScreenElement(
            Vector2 position,
            int width,
            int height,
            SpriteFont spriteFont,
            ITestudinRenderer renderer)
             :base(position, width, height)
        {
            _elapsedTime = 0f;

            _frameCount = 0;

            _framesPerSecond = 0;

            _spriteFont = spriteFont;

            _renderer = renderer;
        }

        #endregion

        #region ScreenElementBase

        public override short ZOrder
        {
            get
            {
                return 0;
            }
        }

        public override bool Visible
        {
            get
            {
                return true;
            }
        }

        public override bool ProcessInput()
        {
            return false;
        }

        public override void Update(GameTime gameTime)
        {
            _elapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

            _frameCount++;

            if (_elapsedTime > 1)
            {
                _framesPerSecond = _frameCount;
                _frameCount = 0;
                _elapsedTime = 0;
            }
        }

        public override void Render()
        {
            _renderer.BeginSpriteBatch();

            _renderer.RenderString(
                _spriteFont,
                "FPS " + ((int)_framesPerSecond).ToString(),
                _position,
                Color.Yellow);

            _renderer.EndSpriteBatch();
        }

        #endregion
    }
}
